package com.example.homework.ui.note_add;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.homework.R;
import com.example.homework.dao.NoteDao;
import com.example.homework.databinding.FragmentNoteAddBinding;
import com.example.homework.pojo.Note;
import com.example.homework.utils.TimeStamp;

import java.text.ParseException;

public class Note_addFragment extends Fragment {
    private EditText note_add;
    private Button note_add_btn;
    NoteDao noteDao;


    private FragmentNoteAddBinding binding;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        Note_addViewModel noteaddViewModel =
                new ViewModelProvider(this).get(Note_addViewModel.class);

        binding = FragmentNoteAddBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        return root;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        note_add = getActivity().findViewById(R.id.note_add);
        note_add_btn = getActivity().findViewById(R.id.note_add_btn);
        noteDao = new NoteDao(getContext());
        String username = getActivity().getIntent().getStringExtra("uname");


        note_add_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String note_text = note_add.getText().toString();
                String note_creater = username;
                Note note = new Note();
                TimeStamp timeStamp = new TimeStamp();
                try {
                    long create_time = timeStamp.getTimeStamp();
                    note.setNote_text(note_text);
                    note.setNote_creater(note_creater);
                    note.setNote_create_time(create_time);
                    long insertNote = noteDao.insertNote(note);
                    if (insertNote != -1) {
                        Toast.makeText(getContext(), "插入成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getContext(), "插入失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}